package com.yyaccp.appinfo.controller;

import com.yyaccp.appinfo.domain.AppInfo;
import com.yyaccp.appinfo.domain.AppVersion;
import com.yyaccp.appinfo.mapper.AppVersionMapper;
import com.yyaccp.appinfo.service.AppInfoService;
import com.yyaccp.appinfo.service.AppVersionService;
import com.yyaccp.appinfo.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Objects;

@RestController
@RequestMapping("/version")
public class AppVersionContRoller {
    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private AppVersionService appVersionService;

    @Autowired
    private AppInfoService appInfoService;

    @RequestMapping("/getById")
    public AjaxResult getById(Long id){
        return AjaxResult.success(appVersionMapper.selectByPrimaryKey(id));
    }

    @RequestMapping("/getByVersionId")
    public AjaxResult getByVersionId(Long versionId){
        return AjaxResult.success(appVersionService.selectByVersionId(versionId));
    }

    @PostMapping("/add")
    public AjaxResult add(AppVersion appVersion, MultipartFile file1 , HttpServletRequest request)throws Exception{
        String path = request.getServletContext().getRealPath("/apks");
        String fileName = file1.getOriginalFilename();
        System.out.println("path:"+path);
        file1.transferTo(new File(path, Objects.requireNonNull(fileName)));
        appVersion.setApkLocPath(path+"\\"+fileName);
        if (appVersionService.add(appVersion) > 0) {
            AppInfo appInfo = new AppInfo();
            appInfo.setId(appVersion.getAppId());
            //获取最新的版本id
            appInfo.setVersionId(appVersionService.getMaxId());
            if (appInfoService.upd(appInfo) > 0) {
                return AjaxResult.success(fileName);
            }
        }
            return AjaxResult.error(fileName);
    }

    @PostMapping("/upd")
    public AjaxResult upd(AppVersion appVersion){
        if (appVersionService.upd(appVersion) > 0) {
            return AjaxResult.success(200);
        }
        return AjaxResult.error(500);
    }
}
